package com.wutong.eams.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wutong.eams.config.RedisConfig;
import redis.clients.jedis.Jedis;

public class RedisUtil {

    private static final Jedis JEDIS = RedisConfig.getJedis();
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    public static <T> void setValue(String key, T value) throws JsonProcessingException {
        String valueStr = OBJECT_MAPPER.writeValueAsString(value);
        JEDIS.set(key, valueStr);
    }

    public static <T> void setValue(String key, T value, long timeoutSec) throws JsonProcessingException {
         String valueStr = OBJECT_MAPPER.writeValueAsString(value);
         JEDIS.setex(key, timeoutSec, valueStr);
    }

    public static void removeValue(String key) {
        JEDIS.del(key);
    }

    public static <T> T getValue(String key, Class<T> clazz) throws JsonProcessingException {
        String valueStr = JEDIS.get(key);
        if (valueStr == null) {
            return null;
        }
        return OBJECT_MAPPER.readValue(valueStr, clazz);
    }

    public static void close() {
        JEDIS.close();
    }
}
